package com.jzo2o.customer.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.common.model.CurrentUser;
import com.jzo2o.common.utils.UserContext;
import com.jzo2o.customer.mapper.BankAccountMapper;
import com.jzo2o.customer.model.domain.BankAccount;
import com.jzo2o.customer.model.dto.response.BankAccountResDTO;
import com.jzo2o.customer.service.IBankAccountService;
import org.springframework.stereotype.Service;

@Service
public class BankAccountServiceImpl extends ServiceImpl<BankAccountMapper, BankAccount> implements IBankAccountService {
    @Override
    public void add(BankAccountResDTO bankAccountResDTO) {
        CurrentUser currentUser = UserContext.getCurrentUser();
        //获取当前用户的id
        Long id = currentUser.getId();
        //根据id查询数据库 有数据就是更新操作没有数据就是新增操作
        BankAccount one = getById(id);
        if (one != null) {
            //更新
            BankAccount bean = BeanUtil.toBean(bankAccountResDTO, BankAccount.class);
            bean.setId(id);
            boolean updateById = updateById(bean);
            if (!updateById) {
                throw new RuntimeException("更新银行账户失败");
            }
            return;
        }
        BankAccount bean = BeanUtil.toBean(bankAccountResDTO, BankAccount.class);
        bean.setId(id);
        boolean save = save(bean);
        if (!save) {
            throw new RuntimeException("添加银行账户失败");
        }
    }

    @Override
    public BankAccountResDTO queryCurrentUserBankAccount() {
        CurrentUser currentUser = UserContext.getCurrentUser();
        //获取当前用户的id
        Long id = currentUser.getId();
        BankAccount bankAccount = getById(id);
        BankAccountResDTO bean = BeanUtil.toBean(bankAccount, BankAccountResDTO.class);
        return bean;
    }
}
